package com.self.war.errorhandler;

import com.vaadin.server.DefaultErrorHandler;
import com.vaadin.server.Sizeable.Unit;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Label;
import com.vaadin.ui.Link;
import com.vaadin.ui.Notification;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;

@SuppressWarnings("serial")
public class AbstractErrorHandler implements IAbtractErrorHandler{

	private UI parent;

	public AbstractErrorHandler() {
		super();
	}

	@Override
	public void error(com.vaadin.server.ErrorEvent event) {
		 // connector event
	    if (event.getThrowable().getCause() instanceof IllegalArgumentException)
	    {
	        IllegalArgumentException exception = (IllegalArgumentException) event.getThrowable().getCause();
	        Notification.show(exception.getMessage(), Notification.Type.ERROR_MESSAGE);
	        parent.setContent(null);
	        return;
	    }
	    
	    // Error on page load. Now it doesn't work. User sees standard error page.
	    if (event.getThrowable() instanceof IllegalArgumentException)
	    {
	        IllegalArgumentException exception = (IllegalArgumentException) event.getThrowable();
	
	        Label label = new com.vaadin.ui.Label(exception.getMessage());
	        label.setWidth(-1, Unit.PERCENTAGE);
	
	        Link goToMain = new Link("Go to main", new com.vaadin.server.ExternalResource("/"));
	
	        VerticalLayout layout = new VerticalLayout();
	        layout.addComponent(label);
	        layout.addComponent(goToMain);
	        layout.setComponentAlignment(label, Alignment.MIDDLE_CENTER);
	        layout.setComponentAlignment(goToMain, Alignment.MIDDLE_CENTER);
	
	        VerticalLayout mainLayout = new VerticalLayout();
	        mainLayout.setSizeFull();
	        mainLayout.addComponent(layout);
	        mainLayout.setComponentAlignment(layout, Alignment.MIDDLE_CENTER);
	
	        Notification.show(exception.getMessage(), Notification.Type.ERROR_MESSAGE);
	        parent.setContent(mainLayout);
	        return;
	    }
	
	    DefaultErrorHandler.doDefault(event);		
	}

	@Override
	public UI getParent() {
		return parent;
	}

	@Override
	public void setParent(UI parent) {
		this.parent = parent;
	}

}